function info() {
	return {
		name : "docs",
		homepage : "http://goofy-yoo.appspot.com/",
		author : {
			name : "Goofy Yoo",
			email : "contact.goofy@gmail.com"
		},
		description : "Search and include documents (doc, pdf, etc) into the email thread",
		usage : [
				"@goofy docs {{{design beyond human abilities}}} \n/bye\n",
				"@goofy docs type:pdf max:1 query:{{{Conscientious Software}}}  \n/bye\n",
				"@goofy docs type:pdf query:{{{kybalion}}} ebook:mobi \n/bye\n" ],
		license : "GPL"
	}
}

function args() {
	return [
			{
				"name" : "query",
				"description" : "Please provide a document query",
				"default" : ""
			},
			{
				"name" : "type",
				"description" : "You can provide a file type (eg. pdf, ppt, doc).",
				"default" : "pdf"
			}, {
				"name" : "max",
				"description" : "Specify maximum number of results ",
				"default" : "1"
			}, {
				"name" : "ebook",
				"description" : "Kindle user? This option triggers eBook conversion command. Valid options are (no|mobi|epub)",
				"default" : "no"
			} ]
}

function execute() {

	var query = ctx.get("query");

	var type = ctx.get("type");

	var max = ctx.get("max");
	
	var ebook = ctx.get("ebook");

	var found = 0;

	var typeEnum = [ "pdf", "ppt", "doc" ];

	if (type != "any")
		found = addHits(ctx, query, type, max, ebook);
	else {
		for ( var i = 0; i < typeEnum.length; i++) {
			if (found < max)
				found += addHits(ctx, query, typeEnum[i], max, ebook)
		}
	}

	var matches = (found == 1) ? "match": "matches";
	
	var txt = "Found " + found + " " + matches + " for <b>" + query
			+ "</b>.";

	if (found > 0)
		txt += " Please find the "+ type +" docs attached.";

	if (ebook != 'no')
		txt += " The eBook file (."+ebook+") will be delivered with the next email.";
		
	ctx.getMessage().addHtmlPart(txt);
}

function addHits(ctx, query, type, max, ebook) {

	var q = "\"" + query + "\"" + " filetype:" + type;

	var url = "http://www.google.com/uds/GwebSearch?context=0&rsz=small&hl=en&source=gsc&gss=.com&gl=www.google.com&v=1.0&q="
			+ Packages.java.net.URLEncoder.encode(q, "UTF-8");

	/*
	 * var url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=" +
	 * Packages.java.net.URLEncoder.encode(q, "UTF-8");
	 */

	var resp = readJSON(url, "UTF-8");

	var hits = 0;

	if (resp.responseStatus == "200") {

		var array = resp.responseData.results;

		for ( var i = 0; i < array.length && i < max; i++) {
			var doc = array[i];
			var docUrl = doc.unescapedUrl;
			ctx.getMessage().attachFile(docUrl);
			addEbookCommand(docUrl, ebook)
			hits++;
		}
	}

	return hits;
}


function addEbookCommand(url, ebook) {
	if (ebook != 'no') {
		var txt = '@goofy ebook-convert url:{{{' + url + '}}} format:' + ebook + ' \n/bye\n';
		ctx.getMessage().attachContent('text/plain', new java.lang.String(txt).getBytes('UTF-8'), 'convert.yoo');
	}
}